package org.adobe.basecode {
	import flash.display.BitmapData;
	import flash.geom.Rectangle;
	import flash.utils.ByteArray;

	/**
	 *  BitmapData转换静态类
	 *  
	 * 	setPixel(j, i, bytes.readUnsignedInt());
	 *  readShort
	 */	
	public class BitmapBytes {
		public function BitmapBytes(){
			throw new Error("BitmapBytes类只是一个静态类!");
		}
		
		/**
		 * BitampData转为二进制
		 * data.rect,writeShort()--data.width,data.height,data.transparent
		 * 
		 * bitmap-->byte
		 * 
		 */		
		public static function encodeByteArray(data:BitmapData):ByteArray {
			if (data == null){
				throw new Error("data参数不能为空!");
			}
			var bytes:ByteArray = data.getPixels(data.rect);
			bytes.writeShort(data.width);
			bytes.writeShort(data.height);
			bytes.writeBoolean(data.transparent);
			bytes.compress();
			return bytes;
		}
		
		/**
		 * BitampData转为Base64字符串 
		 * 
		 * BitampData-->ByteArray-->Base64
		 * 
		 */		
		public static function encodeBase64(data:BitmapData):String {
			return Base64.encodeByteArray(encodeByteArray(data));
		}

		/**
		 * 转换压缩的二进制数据
		 * 
		 * byte-->BitmapData
		 * 
		 */		
		public static function decodeByteArray(bytes:ByteArray):BitmapData {
			if (bytes == null){
				throw new Error("bytes参数不能为空!");
			}
			if (bytes.length < 6){
				throw new Error("bytes参数为无效值!");
			}
			bytes.uncompress();
			bytes.position = bytes.length - 1;
			var transparent:Boolean = bytes.readBoolean();
			bytes.position = bytes.length - 3;
			var height:int = bytes.readShort();
			bytes.position = bytes.length - 5;
			var width:int = bytes.readShort();
			bytes.position = 0;
			
			var datas:ByteArray = new ByteArray();
			bytes.readBytes(datas, 0, bytes.length - 5); //剩余字节数写入bytes
			var bmp:BitmapData = new BitmapData(width, height, transparent, 0);
			bmp.setPixels(new Rectangle(0, 0, width, height), datas);
			return bmp;
		}

		/**
		 * base64数据转换为BitmapData
		 * base64--->byte--->BitmapData 
		 * @param data
		 * @return 
		 * 
		 */		
		public static function decodeBase64(data:String):BitmapData {
			return decodeByteArray(Base64.decodeToByteArray(data));
		}
	}
}